package main

import (
	"crypto/sha256"
	"encoding/base64"
	"flag"
	"osiris/config"
	"osiris/core"
	"osiris/logger"
	"osiris/ocrypto/ed25519"
	"osiris/proc"
	"strings"
)

func main() {
	// Parse options from the command line
	httpServerPort := flag.Int("p", 8888, "http server port")
	p2pListenPort := flag.Int("l", 10000, "wait for incoming connections")
	privKeyStr := flag.String("k", "", "private key for identity the p2p node")
	bootstrap := flag.Bool("bs", false, "start as a bootstrap peer")
	//command := flag.Bool("command", true, "enable command control. disable all the std print which isn't produced by command if enable")
	flag.Parse()

	//如果没有指定节点的私钥，默认用私钥文件里的私钥
	if *privKeyStr == "" {
		*privKeyStr = ed25519.GetPeerPrivKeyStr()
	}
	configCodeName(*privKeyStr)

	//开启节点启动的协程池
	proc.StartProc(*httpServerPort, *p2pListenPort, *privKeyStr, *bootstrap).Execute()

	//等待节点关闭的信号
	terminateProc, exitWG := proc.TerminateProc()
	sig := <-core.Quit
	close(core.Quit)

	//开启节点关闭的协程池
	logger.EnableStdLog()
	logger.Printf("terminate for sig: %s\n", sig)
	terminateProc.Execute()
	exitWG.Wait()
}

// configCodeName 根据私钥hash前32个字节设置日志子路径,没指定密钥将随机生成密钥，随机生成的密钥的节点没子路径
//
//	@param privKeyStr 节点的ed25519私钥字符串
//	@return string 节点的代号
func configCodeName(privKeyStr string) string {
	hash := sha256.Sum256([]byte(privKeyStr))
	nodeCodeName := base64.StdEncoding.EncodeToString(hash[:32])
	nodeCodeName = keepAlphabets(nodeCodeName)
	config.NodeCodeName = nodeCodeName
	logger.SetSubPath(nodeCodeName)

	return nodeCodeName
}

func keepAlphabets(s string) string {
	alphabets := "abcdefghijklmnopqrstuvwxyz"
	var result strings.Builder

	for _, char := range s {
		if strings.ContainsRune(alphabets, char) {
			result.WriteRune(char)
		}
	}

	return result.String()
}
